﻿// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone

using BlazorAdmin.Caching;
using BlazorAdmin.Interface;
using BlazorAdmin.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using BlazorAdmin.Services.DbService;

namespace BlazorAdmin.Services
{
    internal class AppService : BaMgmtDbService, IApp
    {
        private const string AppServiceGetAppsByRoleIdCacheKey = "AppService-GetAppsByRoleId";

        public AppService(IPetaPoco db) : base(db) { }

        public List<string> GetAppsByRoleId(int roleId) => CacheManager.GetOrAdd($"{AppServiceGetAppsByRoleIdCacheKey}-{roleId}",
            entry => Fetch<string>("SELECT AppID FROM RoleApp WHERE RoleID = @0", roleId));

        public bool SaveAppsByRoleId(int roleId, IEnumerable<string> appIds)
        {
            var ret = false;
            using var db = Create();
            try
            {
                db.BeginTransaction();
                db.Execute("DELETE FROM RoleApp WHERE RoleID = @0", roleId);
                db.InsertBatch("RoleApp", appIds.Select(g => new { AppID = g, RoleID = roleId }));
                db.CompleteTransaction();
                ret = true;
            }
            catch (Exception)
            {
                db.AbortTransaction();
                throw;
            }
            if (ret)
            {
                CacheManager.Clear();
            }
            return ret;
        }
    }
}